package com.demo.htmltopng.util;

import gui.ava.html.image.generator.HtmlImageGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Html2Image转换工具
 * @author luzck
 * @since 2022/7/2
 */
@Slf4j
public class Html2ImageUtil {

    public static Map<String, Object> htmlToImage(String htmlTemplate) throws InterruptedException {
        Map<String, Object> data = new HashMap<>(3);
        System.out.println("------------开始HTML转图片-----------------");
        Date start = new Date();

        HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
        //加载html模版
        imageGenerator.loadHtml(htmlTemplate);

        int img = htmlTemplate.indexOf("<img");
        // 当html代码里带有图片时，生成的程序必须有一定的等待时间
        // 初步估计是工具加载流未完成就进行图片的生成以及保存工作
        if (img > 0) {
            Thread.sleep(1000);
        }

        BufferedImage bufferedImage = getGrayPicture(imageGenerator.getBufferedImage());
        Thread.sleep(1000);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ConvertToMultipartFile convertToMultipartFile = null;
        FileOutputStream fileOutputStream = null;
        try {
            ImageIO.write(bufferedImage, "jpg", outputStream);
            byte[] imageByte = outputStream.toByteArray();
            String path = System.getProperty("user.dir");
            fileOutputStream = new FileOutputStream(path + File.separator + "html2Image.jpg");
            fileOutputStream.write(outputStream.toByteArray());
            convertToMultipartFile = new ConvertToMultipartFile(imageByte, "newNamepic", "pic1.jpg", "jpg", imageByte.length);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Date end = new Date();
        long diff = (end.getTime() - start.getTime()) / 1000;
        System.out.println("总费时：" + diff + "秒");
        System.out.println("------------结束HTML转图片-----------------");
        data.put("file", convertToMultipartFile);
        //String url = ossService.upload((MultipartFile) convertToMultipartFile);
        data.put("width", bufferedImage.getWidth());
        data.put("height", bufferedImage.getHeight());
        return data;
    }

    /**
     * jpg
     * 重新设置画布背景颜色
     * @param originalImage BufferedImage
     * @return BufferedImage
     */
    public static BufferedImage getGrayPicture(BufferedImage originalImage)
    {
        BufferedImage grayPicture;
        int imageWidth = originalImage.getWidth();
        int imageHeight = originalImage.getHeight();

        grayPicture = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_INT_RGB);
        ColorConvertOp cco = new ColorConvertOp(ColorSpace
                .getInstance(ColorSpace.CS_GRAY), null);
        cco.filter(originalImage, grayPicture);

        Graphics2D graphics = originalImage.createGraphics();
        // 抗锯齿
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.dispose();
        return grayPicture;
    }

}
